package com.peng.test.jdk;

import java.util.Optional;

import org.junit.jupiter.api.Test;
import org.slf4j.Logger;
import org.slf4j.LoggerFactory;

import lombok.AllArgsConstructor;
import lombok.Data;
import lombok.NoArgsConstructor;

/**
 * OptionalSample
 * 对null进行强转如果是对象本身的话不会报错
 * 如果将 Integer类型 的null 强转成int类型会报错，因为底层会调用Integer.intValue() 方法
 *
 * @author lupeng
 * Created on 2022-05-06
 */
public class OptionalSample {

    private static final Logger logger = LoggerFactory.getLogger(OptionalSample.class);

    @Test
    public void s1() {
        Person person = null;
        Man man = (Man) Optional.ofNullable(person)
                .orElse(null);
        System.out.println(man);
    }

    @Test
    public void s2() {
        Person o = (Person) null;
        System.out.println(o);
    }

    @Test
    public void s3() {
        Object o = null;
        Integer i = (Integer) o;
        System.out.println(i);
    }

    @Test
    public void s4() {
        Object o = null;
        int i = (Integer) o;
        System.out.println(i);
        // java.lang.NullPointerException: Cannot invoke "java.lang.Integer.intValue()" because "o" is null
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Person {
        private String name;
    }

    @Data
    @AllArgsConstructor
    @NoArgsConstructor
    static class Man extends Person {
        private String name;
        private int age;
    }
}
